﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using Scenario;
using TMPro;
using UI;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace UI
{
    public class UI_DetailPanel : MonoBehaviour
    {
        private static UI_DetailPanel _instance;

        private int m_stack;
        
        private void Awake()
        {
            _instance = this;
        }
        private void OnEnable()
        {
            PlayerController.SetPause(true);
        }
        private void OnDisable()
        {
            PlayerController.SetPause(false);
        }

        private void TriggerInternal(DetailInfo info)
        {
            var item = GameObject.Instantiate(info.uiPrefab, transform, false).transform;
            item.Find("CloseBtn").GetComponent<Button>().onClick.AddListener(() =>
            {
                GameObject.DestroyImmediate(item.gameObject);
                m_stack--;
                if (m_stack == 0) gameObject.SetActive(false);
            });
            var itemInfos = item.GetComponentsInChildren<ItemInfo>(false);
            for (var i = itemInfos.Length - 1; i >= 0; i--)
            {
                var itemInfo = itemInfos[i];
                itemInfo.GetComponent<Button>().onClick.AddListener(() =>
                {
                    PlayerController.GetItem(itemInfo);
                });
            }
            var itemTriggers = item.GetComponentsInChildren<ItemTrigger>(false);
            for (var i = itemTriggers.Length - 1; i >= 0; i--)
            {
                var trigger = itemTriggers[i];
                trigger.GetComponent<Button>().onClick.AddListener(() =>
                {
                    PlayerController.UseItem(trigger, null);
                });
            }
            var detailInfos = item.GetComponentsInChildren<DetailInfo>(false);
            for (var i = detailInfos.Length - 1; i >= 0; i--)
            {
                var detailInfo = detailInfos[i];
                detailInfo.GetComponent<Button>().onClick.AddListener(() =>
                {
                    PlayerController.InteractDetail(detailInfo);
                });
            }
            var gameTriggers = item.GetComponentsInChildren<GameTrigger>(false);
            for (var i = gameTriggers.Length - 1; i >= 0; i--)
            {
                var trigger = gameTriggers[i];
                trigger.GetComponent<Button>().onClick.AddListener(() =>
                {
                    PlayerController.InteractGame(trigger);
                });
            }

            m_stack++;
        }
        
        public static void Trigger(DetailInfo detailInfo)
        {
            if (!_instance.gameObject.activeSelf) _instance.gameObject.SetActive(true);
            _instance.TriggerInternal(detailInfo);
        }
    }
}
